# -*- coding: utf-8 -*-

import click
from flask.cli import AppGroup
from application.models import UserModel
from application.extensions import db

user_cli = AppGroup('users', help="User related commands")

@user_cli.command('create')
@click.option('--username', prompt=True, help='The username used to login.')
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True, help='The password used to login.')
def create_admin(username, password):
    """Create an admin."""
    db.create_all()

    user = UserModel.query.first()
    if user is not None:
        click.echo('Updating user...')
        user.email = username
        user.set_password(password)  # 设置密码
    else:
        click.echo('Creating user...')
        user = UserModel(email=username, name='Admin')
        user.set_password(password)  # 设置密码
        db.session.add(user)

    db.session.commit()  # 提交数据库会话
    click.echo('Done.')